import mammoth from "mammoth";
import JSZip from 'jszip'
import request from "@/utils/request";


async function extractPptxText(arrayBuffer) {
  const zip = await JSZip.loadAsync(arrayBuffer)
  const slideFiles = Object.keys(zip.files).filter(name => name.startsWith('ppt/slides/slide') && name.endsWith('.xml'))
  const texts = []

  for (const file of slideFiles.sort()) {
    const xmlText = await zip.file(file).async('string')
    const parser = new DOMParser()
    const xmlDoc = parser.parseFromString(xmlText, 'text/xml')
    const textNodes = xmlDoc.querySelectorAll('a\\:t, t') // 兼容命名空间
    const slideText = Array.from(textNodes).map(n => n.textContent).join('')
    texts.push(slideText)
  }

  return texts
}

// 工具函数：将 File Blob 转为 ArrayBuffer
export function readFileAsArrayBuffer(file) {
  return new Promise((resolve, reject) => {
    const reader = new FileReader();
    reader.onload = () => resolve(reader.result);
    reader.onerror = () => reject(reader.error);
    reader.readAsArrayBuffer(file);
  });
}

export function readFilePPT(path) {
  // 单个 GET 请求设置超时时间为  秒
  return axios.get(process.env.VUE_APP_BASE_API + '/common/review/' + path, {
    timeout: 90000  // 仅对当前请求生效
  });
}

export function readFilePDF(id) {
  // 单个 GET 请求设置超时时间为  秒
  return axios.get(process.env.VUE_APP_BASE_API + '/common/pdf/' + id, {
    timeout: 60000  // 仅对当前请求生效
  });
}

export async function readWordAsArrayBuffer(word) {
  // 用 mammoth 解析 .docx 文件
  let arrayBuffer = await readFileAsArrayBuffer(word);
  // console.log(arrayBuffer)
  let buffer = null
  await mammoth.convertToHtml({arrayBuffer})
    .then(result => {
      buffer = result.value; // 获取转换后的 HTML
    }).catch(error => {
      console.error('转换失败：', error);
    });
  return buffer
}

export async function readWordAsBlob(wordUrl) {
  //下载远程 .docx 文件为 Blob
  const response = await axios({
    url: wordUrl,
    method: 'GET',
    responseType: 'blob' // 关键：指定响应类型为 Blob
  });
  // console.log(response)

  // 校验响应的 Content-Type
  if (!response.headers['content-type'].includes('application/vnd.openxmlformats-officedocument.wordprocessingml.document')) {
    throw new Error('文件不是 .docx 格式');
  }

  const docxBlob = response.data; // Blob 类型的 .docx 文件
  // console.log(docxBlob)
  return readWordAsArrayBuffer(docxBlob)

}
